package leetcode; /**
 * description:
 * author:张腾
 * date:2021-07-25
 */

/**
 * 给定两个大小分别为 m 和 n 的正序（从小到大）数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数
 */
public class leetcode4 {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int n1 = nums1.length, n2 = nums2.length;
        int[] nums = new int[n1+n2];
        int p1=0, p2=0, index=0;
        while (p1<n1 && p2<n2){
            if (nums1[p1]<nums2[p2]){
                nums[index] = nums1[p1];
                p1++;
            }else{
                nums[index] = nums2[p2];
                p2++;
            }
            index++;
        }
        if (p1!=n1){
            while (p1<n1) nums[index++] = nums1[p1++];
        }
        if (p2!=n2){
            while (p2<n2) nums[index++] = nums2[p2++];
        }
        double ans = 0;
        int i = (n1+n2-1)/2;
        if ((n1+n2)%2==0){
            ans = ((double)(nums[i]+nums[i+1]))/2;
        }else{
            ans = nums[i];
        }
        return ans;
    }
}
